package org.larkdoc.auth;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

/**
 * 自定义请求过滤器： 把ajax请求由url跳转改为ajax响应
 * 
 * @author  zhangpeijun
 * @version  [v1.0.1, 2017年3月14日]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class JsonFormAuthenticationFilter extends FormAuthenticationFilter {
    
    private final static Logger LOG       = LoggerFactory.getLogger(JsonFormAuthenticationFilter.class);
    
    /**
     * XMLHttpRequest
     */
    public static String        AJAX_HEAD = "XMLHttpRequest";
    
    /**
     * X-Requested-With
     */
    public static String        HTTP_AJAX = "X-Requested-With";
    
    /**
     * 所有请求都会走此方法
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                return executeLogin(request, response);
            } else {
                LOG.info("Login request is not post");
                //allow them to see the login page ;)
                return true;
            }
        } else {
            
            saveRequestAndRedirectToLogin(request, response);
            return false;
        }
    }
    
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
                                     ServletResponse response) throws Exception {
        if (!isAjaxRequest((HttpServletRequest)request)) {
            issueSuccessRedirect(request, response);
        }
        return false;
    }
    
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request,
                                     ServletResponse response) {
        if (isAjaxRequest((HttpServletRequest)request)) {
            // 新增方法，增加ajax登录请求处理
            // TODO 异常识别
            /*RespBaseVO vo = new RespBaseVO();
            vo.setRetCode(ViewConts.Code.USER_ERROR);
            vo.setRetMsg(ViewConts.Msg.USER_ERROR);
            writeToResponse(response, vo);*/
        } else {
            setFailureAttribute(request, e);
        }
        return true;
    }
    
    public void writeToResponse(ServletResponse response, Object obj) {
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            pw.write(JSONObject.toJSONString(obj));
        } catch (IOException e) {
            LOG.error("writeToResponse IOException", e);
        } finally {
            if (null != pw) {
                pw.flush();
                pw.close();
            }
        }
    }
    
    public boolean isAjaxRequest(HttpServletRequest request) {
        return AJAX_HEAD.equalsIgnoreCase(request.getHeader(HTTP_AJAX));
    }
}
